package cn.piggy.gateway.core.proxy.cglib;

import cn.piggy.gateway.core.proxy.MyGenericReference;
import cn.piggy.gateway.core.session.GatewaySession;
import net.sf.cglib.proxy.Enhancer;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class MapperProxyFactory {

    private String uri;

    public MapperProxyFactory(String uri) {
        this.uri = uri;
    }

    private final Map<String, MyGenericReference> genericReferenceCache = new ConcurrentHashMap<>();

    public MyGenericReference newInstance(GatewaySession gatewaySession) {
        // uri
        return genericReferenceCache.computeIfAbsent(uri, k -> {
            // 泛化调用
            MapperProxy genericReferenceProxy = new MapperProxy(gatewaySession);
            // 代理对象
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(Object.class);

            // MyGenericReference 统一泛化调用接口
            enhancer.setInterfaces(new Class[]{MyGenericReference.class});
            enhancer.setCallback(genericReferenceProxy);
            return (MyGenericReference) enhancer.create();
        });
    }

}